/** 
*@Project: UIBase
*@File: ItemAdapter.java
*@Author: linlin.zou
*@Date: 2014-12-3 
*@Copyright: 2014 www.boshtc.com Inc. All rights reserved.


*/ 
package com.alipear.uibase;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

public class ItemAdapter<E> extends BaseAdapter {

    Drawable mDefaultDrawable = null;

    Context c;
    List<E> mItemList = new ArrayList<E>();
    protected View mSearchView = null;
    ItemLayout<E> mUserLayout = null;
    ImageLoadWrapper mImageLoader;
    public ItemAdapter(Context c, boolean enableImageLoader,
                       ItemLayout<E> userLayout) {
        super();
        init(c, enableImageLoader,null, userLayout);
    }
    
    public ItemAdapter(Context c, boolean itemWithWebIamge, List<E> bl,
                       ItemLayout<E> userLayout) {
        super();
        init(c,itemWithWebIamge, bl, userLayout);
    }

    private void init(Context c, boolean itemWithWebIamge, List<E> bl,
                      ItemLayout<E> userLayout) {
        this.c = c;
        mItemList = bl;
        mUserLayout = userLayout;
        if (itemWithWebIamge) {
            mImageLoader = new ImageLoadWrapper(c);
        }
    }
    
    public void setList(List<E> list) {
        mItemList = list;   
        this.notifyDataSetChanged();
    }

    @SuppressWarnings("unchecked")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewFinder holder;

        if (convertView != null) {
            holder = (ViewFinder) convertView.getTag();
            if (holder != null) {
                convertView = null;
            }
        }

        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(
                    mUserLayout.getLayoutId(), null);
            if (mImageLoader != null) {
                holder = new ViewFinder(convertView,mImageLoader);
            }
            else {
                holder = new ViewFinder(convertView);
            }
            convertView.setTag(holder);
        }
        else {
            holder = (ViewFinder) convertView.getTag();
        }
        holder.setItemIndex(position);

        E item = getItem(position);

        mUserLayout.setItemOtherValues(item, holder);
        return convertView;
    }

    @Override
    public int getCount() {
        return mItemList.size();
    }

    @Override
    public E getItem(int position) {
        return mItemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}